package com.offcn.sellergoods.controller;

import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.sellergoods.pojo.Item;
import com.offcn.sellergoods.service.ItemService;
import com.offcn.utils.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/item")
public class ItemController {

    @Autowired
    private ItemService itemService;

    @GetMapping("/")
    public Result<List<Item>> findAll(){
        List<Item> itemList = itemService.findAll();
        return new Result<>(true, StatusCode.OK,itemList,"查询sku数据成功");
    }

    @GetMapping("/{id}")
    public Result<Item> findItemById(@PathVariable("id") Long id){
        Item item = itemService.findItemById(id);
        return new Result<>(true,StatusCode.OK,item,"查询成功");
    }

    @PostMapping("/decr")
    public Result decrNum(){
        // 获取令牌
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String token = details.getTokenValue();
        String username = TokenDecode.getUsername(token);
        try {
            itemService.decrNum(username);
            return new Result(true,StatusCode.OK,"成功减少库存");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,e.getMessage());
        }
    }
}
